<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    width="500px"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" @change="change" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import { apiUpdateUser, apiCreateUser } from '@/api/sys/user';
  import { apiGetDeptTreeList } from '@/api/sys/dept';
  import { DeptTreeListItem } from '@/api/sys/model/deptModel';
  import { UserListItem } from '@/api/sys/model/userModel';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref(0);

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        const values = data.record;
        ///values.avatar_arr = []; //用于表单字段
        if (unref(isUpdate)) {
          // console.log('values?.avatar', values?.avatar);
          // if (values?.avatar) {
          //   values.avatar_arr = [values.avatar];
          // } else {
          //   values.avatar_arr = [];
          // }
          rowId.value = data.record.uid;
          setFieldsValue({
            ...values,
          });
        }

        const treeData = await apiGetDeptTreeList();
        treeData.push({ dept_name: '选择部门', dept_id: 0 } as DeptTreeListItem);
        updateSchema([
          {
            field: 'dept_id',
            componentProps: { treeData },
          },
          {
            field: 'username',
            componentProps: { disabled: !!unref(isUpdate) },
          },
          {
            field: 'password',
            required: !unref(isUpdate),
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        try {
          const values = (await validate()) as UserListItem;
          // console.log('values--', values);
          // if (values?.avatar_arr.length > 0) {
          //   values.avatar = values.avatar_arr[0];
          // } else {
          //   values.avatar = '';
          // }
          setDrawerProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            apiUpdateUser({ ...values, uid: rowId.value })
              .then(() => {
                closeDrawer();
                emit('success', {
                  isUpdate: unref(isUpdate),
                  values: { ...values },
                });
              })
              .catch((err) => {
                console.log('updateDept', err);
              });
          } else {
            apiCreateUser(values)
              .then(() => {
                closeDrawer();
                emit('success', {
                  isUpdate: unref(isUpdate),
                  values: { ...values },
                });
              })
              .catch((err) => {
                console.log('createDept', err);
              });
          }
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      const change = (s) => {};
      return { registerModal, registerForm, getTitle, handleSubmit, change };
    },
  });
</script>
